import React, { useEffect } from 'react';
import { Modal, Button } from 'antd';
import useSyncState from '../hooks/useSyncState';
import { useMenuContext } from '../Context/MenuContext';
import SelectClient from './SelectClient';
import SelectVariable from './SelectVariable';
import { IStream, IVariableList } from '@/modules/interface';
import styled from '@emotion/styled';
import { ArrowLeftOutlined } from '@ant-design/icons';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import AgentService from '@/modules/Agent';
import { useTranslation } from 'react-i18next';
import { IBusinessName, useBusiness } from '../Context/BusinessContext';

interface CollVariableProps {
	visible: boolean;
}

const BtnBox = styled.div``;

const BackBox = styled.div`
	visibility: ${props => (!props.isSingleRole ? 'visible' : 'hidden')};
	cursor: pointer;
	.back-text {
		font-size: 13px;
		color: #202020;
		margin-left: 4px;
	}
`;

const Footer = styled.div`
	display: flex;
	align-items: center;
	justify-content: space-between;
`;

const index = (props: CollVariableProps) => {
	const { visible } = props;

	const { t } = useTranslation();

	const { setMenuState } = useMenuContext();

	const { sendBusiness } = useBusiness();

	const [page, setPage] = useSyncState<number>(1);

	const [variableTitle, setVariableTitle] = useSyncState<string>(`${t('bianliangshouji')}（${page()}/2）`);

	const defaultCheckedList: CheckboxValueType[] = [];
	const [checkedVariablesList, setCheckedVariablesList] = useSyncState<CheckboxValueType[]>(defaultCheckedList);

	const [checkVariablesListAll, setCheckVariablesListAll] = useSyncState(false);

	const [clientInforMation, setClientInforMation] = useSyncState<IStream | null>(null);

	const [errorMessage, setErrorMessage] = useSyncState<string>('');

	const [variableList, setVariableList] = useSyncState<IVariableList[]>([]);

	const handleOk = () => {
		if (checkedVariablesList().length === 0) {
			setErrorMessage(t('select-collect-variable'));
			return;
		}
		//发送给访客的变量
		const variableData = variableList().filter(item => checkedVariablesList().includes(item.id));
		sendBusiness(IBusinessName.SEND_VARIABLE_COLLECTION, { data: variableData, role: clientInforMation()?.customerRole, businessId: AgentService.bizScenarioId }, [
			clientInforMation()?.clientId as string
		]);
		setMenuState(prevState => ({ ...prevState, showVariableView: false }));
		initData();
	};

	const handleCancel = () => {
		setMenuState(prevState => ({ ...prevState, showVariableView: false }));
		initData();
	};

	const back = () => {
		initData();
	};

	const selectRole = (stream: IStream) => {
		console.log('selectRole:', stream);

		setClientInforMation(stream);
		setPage(2);
		setVariableTitle(`${t('bianliangshouji')}（${page()}/2）`);
		setVariableList(AgentService.customerVariableList.filter(item => item.roleName === clientInforMation()?.customerRole));
	};

	const onCheckVariablesListAllChange = (e: CheckboxChangeEvent) => {
		setCheckedVariablesList(e.target.checked ? variableList().map(item => item.id) : []);
		setCheckVariablesListAll(e.target.checked);
	};

	const onChangeVariablesList = (e: CheckboxValueType[]) => {
		setCheckedVariablesList(e);
		setCheckVariablesListAll(e.length === variableList().length);
	};

	useEffect(() => {
		return () => {
			initData();
		};
	}, []);

	useEffect(() => {
		console.log('useEffect:', isSingleRole(), variableList(), AgentService.customerVariableList, AgentService.getAllMediaSteams());
		if (!isSingleRole()) {
			setVariableList(AgentService.customerVariableList.filter(item => item.roleName === clientInforMation()?.customerRole));
			setVariableTitle(`${t('bianliangshouji')}（${page()}/2）`);
		} else {
			const stream = AgentService.getAllMediaSteams().find(item => item.label && item.label.includes('customer'));

			if (!stream) return;
			setClientInforMation(stream);
			setVariableTitle(`${t('bianliangshouji')}`);
			setVariableList(AgentService.customerVariableList.filter(item => item.roleName === stream.customerRole));
		}
	}, [props]);

	const initData = () => {
		setPage(1);

		setVariableTitle(`${t('bianliangshouji')}（${page()}/2）`);
		setCheckedVariablesList(defaultCheckedList);
		setCheckVariablesListAll(false);
		setClientInforMation(null);
		setErrorMessage('');
		setVariableList([]);
	};

	const isSingleRole = () => {
		const list = AgentService.getAllMediaSteams().filter(item => item.label && item.label.includes('customer'));
		return list.length === 1;
	};

	return (
		<div>
			<Modal
				title={variableTitle()}
				destroyOnClose={true}
				open={visible}
				onOk={handleOk}
				onCancel={handleCancel}
				className="collectVariable-modal"
				footer={
					page() === 1 && !isSingleRole() ? null : (
						<Footer>
							<BackBox onClick={back} isSingleRole={isSingleRole()}>
								<ArrowLeftOutlined width={15} height={12} />
								<span className="back-text">{t('back')}</span>
							</BackBox>
							<BtnBox>
								<Button key="back" onClick={handleCancel}>
									{t('cancel')}
								</Button>
								<Button key="submit" type="primary" onClick={handleOk}>
									{t('confirm-the-collect')}
								</Button>
							</BtnBox>
						</Footer>
					)
				}
			>
				{page() === 1 && !isSingleRole() ? (
					<SelectClient selectRole={selectRole} />
				) : (
					<SelectVariable
						variableList={variableList()}
						checkedVariablesList={checkedVariablesList()}
						onCheckVariablesListAllChange={onCheckVariablesListAllChange}
						checkVariablesListAll={checkVariablesListAll()}
						onChangeVariablesList={onChangeVariablesList}
						errorMessage={errorMessage()}
					/>
				)}
			</Modal>
		</div>
	);
};

export default index;
